import 'dart:io';

import 'package:auto_route/auto_route.dart';
import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/common/widget/character_count_text_field.dart';
import 'package:casdon/common/widget/common_app_bar.dart';
import 'package:casdon/common/widget/common_video_player.dart';
import 'package:casdon/common/widget/fullscreen_loading_overlay.dart';
import 'package:casdon/common/widget/primary_button.dart';
import 'package:casdon/core/utils/toast_utils.dart';
import 'package:casdon/modules/feedback/data/api/feedback_reply_api.dart';
import 'package:casdon/modules/feedback/providers/feedback_provider.dart';
import 'package:casdon/modules/feedback/ui/components/feedback_media_preview.dart';
import 'package:casdon/modules/lifeCircle/ui/screen/image_browser_screen.dart';
import 'package:casdon/modules/me/application/notification/oss_sts_notifier.dart';
import 'package:casdon/modules/me/application/notification/image_picker_notifier.dart';
import 'package:casdon/modules/me/application/notification/user_info_notifier.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:video_player/video_player.dart';

@RoutePage()
class FeedbackContinueScreen extends ConsumerStatefulWidget {
  final String feedbackInfoId;

  const FeedbackContinueScreen({super.key, required this.feedbackInfoId});

  @override
  ConsumerState<FeedbackContinueScreen> createState() =>
      _FeedbackContinueScreenState();
}

class _FeedbackContinueScreenState
    extends ConsumerState<FeedbackContinueScreen> {
  final TextEditingController _contentController = TextEditingController();
  final List<File> _selectedImages = [];
  final List<File> _selectedVideos = [];
  bool _isSubmitting = false;

  @override
  void dispose() {
    _contentController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final scaffold = Scaffold(
      appBar: const CommonAppBar(title: '意见反馈'),
      backgroundColor: context.colorScheme.surface,
      body: Column(
        children: [
          ColoredBox(
            color: context.colorScheme.surface,
            child: SizedBox(height: 10.h, width: double.infinity),
          ),
          Expanded(
            child: SafeArea(
              top: false,
              child: SingleChildScrollView(
                child: Container(
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(12),
                  ),
                  padding: EdgeInsets.all(16.w),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      _buildContentEditor(context),
                      SizedBox(height: 16.h),
                      _buildMediaSection(context),
                    ],
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
      bottomNavigationBar: _buildBottomBar(context),
    );

    return FullscreenLoadingOverlay(loading: _isSubmitting, child: scaffold);
  }

  Widget _buildContentEditor(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Text(
              '反馈内容',
              style: context.textTheme.bodyLarge?.copyWith(
                color: context.customColorThemeNonNull.textColor1,
              ),
            ),
            const SizedBox(width: 4),
            const Text('*', style: TextStyle(color: Colors.red)),
          ],
        ),
        SizedBox(height: 8.h),
        CharacterCountTextField(
          controller: _contentController,
          hintText: '请输入反馈内容',
          maxLength: 500,
          maxLines: 5,
          showDoneAction: true,
        ),
      ],
    );
  }

  Widget _buildMediaSection(BuildContext context) {
    final totalCount = _selectedImages.length + _selectedVideos.length;
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '添加图片或视频（可选，最多3个文件，其中最多1个视频，视频时长不超过30秒）',
          style: context.textTheme.bodyMedium?.copyWith(
            color: context.customColorThemeNonNull.textColor2,
          ),
        ),
        SizedBox(height: 8.h),
        Wrap(
          spacing: 8.w,
          runSpacing: 8.h,
          children: [
            ..._selectedImages.map(
              (image) => FeedbackMediaPreview(
                source: image.path,
                height: 68.w,
                width: 68.w,
                isVideo: false,
                onDelete: () {
                  setState(() {
                    _selectedImages.remove(image);
                  });
                },
                onTap: _handleMediaTap,
              ),
            ),
            ..._selectedVideos.map(
              (video) => FeedbackMediaPreview(
                source: video.path,
                isVideo: true,
                height: 68.w,
                width: 68.w,
                customVideoBuilder: (path) => _VideoThumbnail(videoPath: path),
                onDelete: () {
                  setState(() {
                    _selectedVideos.remove(video);
                  });
                },
                onTap: _handleMediaTap,
              ),
            ),
            if (totalCount < 3)
              _buildMediaButton(
                icon: Icons.image_outlined,
                label: '图片',
                onTap: _pickImages,
              ),
            if (_selectedVideos.isEmpty && totalCount < 3)
              _buildMediaButton(
                icon: Icons.videocam_outlined,
                label: '视频',
                onTap: _pickVideo,
              ),
          ],
        ),
      ],
    );
  }

  void _handleMediaTap(String source, bool isVideo) {
    if (isVideo) {
      _openVideoPreview(source);
    } else {
      _openImagePreview(source);
    }
  }

  void _openImagePreview(String source) {
    List<String> images = _selectedImages.map((img) => img.path).toList();
    var initialIndex = images.indexOf(source);
    if (images.isEmpty) {
      images = [source];
      initialIndex = 0;
    } else if (initialIndex < 0) {
      images = [...images, source];
      initialIndex = images.length - 1;
    }

    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (_) => Center(
          child: ImageBrowserScreen(
            imageUrls: images,
            initialIndex: initialIndex,
          ),
        ),
      ),
    );
  }

  void _openVideoPreview(String source) {
    final videoSource = _isNetworkPath(source)
        ? VideoSource.network(source)
        : VideoSource.file(File(source));

    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (_) => _VideoPreviewScreen(videoSource: videoSource),
      ),
    );
  }

  bool _isNetworkPath(String path) {
    final uri = Uri.tryParse(path);
    return uri != null && uri.hasScheme && uri.host.isNotEmpty;
  }

  Widget _buildMediaButton({
    required IconData icon,
    required String label,
    required VoidCallback onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        width: 68.w,
        height: 68.w,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(12.r),
          border: Border.all(
            color:
                context.customColorThemeNonNull.gray2 ?? Colors.grey.shade300,
          ),
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(icon, color: context.customColorThemeNonNull.textColor2),
            SizedBox(height: 4.h),
            Text(
              label,
              style: context.textTheme.bodySmall?.copyWith(
                color: context.customColorThemeNonNull.textColor2,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildBottomBar(BuildContext context) {
    return Container(
      color: Colors.white,
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
      child: SafeArea(
        top: false,
        child: PrimaryButton(
          text: '提交',
          onPressed: _isSubmitting ? null : _handleSubmit,
        ),
      ),
    );
  }

  Future<void> _pickImages() async {
    final totalCount = _selectedImages.length + _selectedVideos.length;
    final remaining = 3 - totalCount;
    if (remaining <= 0) {
      ToastUtil.show('最多只能选择3个文件');
      return;
    }

    final notifier = ref.read(imagePickerNotifierProvider.notifier);
    final result = await notifier.pickFromGallery(
      context: context,
      config: ImagePickerConfig(
        pickerType: PickerType.imageOnly,
        maxImages: remaining,
      ),
    );

    if (result == null || !result.hasData || !mounted) {
      return;
    }

    setState(() {
      final allowed = 3 - (_selectedImages.length + _selectedVideos.length);
      _selectedImages.addAll(result.images.take(allowed));
    });
  }

  Future<void> _pickVideo() async {
    if (_selectedVideos.isNotEmpty) {
      ToastUtil.show('最多只能选择1个视频');
      return;
    }

    final totalCount = _selectedImages.length + _selectedVideos.length;
    if (totalCount >= 3) {
      ToastUtil.show('最多只能选择3个文件');
      return;
    }

    final notifier = ref.read(imagePickerNotifierProvider.notifier);
    final result = await notifier.pickFromGallery(
      context: context,
      config: const ImagePickerConfig(
        pickerType: PickerType.videoOnly,
        maxVideos: 1,
      ),
    );
    if (result == null || !result.hasData || !mounted) {
      return;
    }

    setState(() {
      _selectedVideos
        ..clear()
        ..addAll(result.videos.take(1));
    });
  }

  Future<void> _handleSubmit() async {
    if (_contentController.text.trim().isEmpty) {
      ToastUtil.show('请输入反馈内容');
      return;
    }

    if (_isSubmitting) return;

    setState(() {
      _isSubmitting = true;
    });

    try {
      String ossIds = '';
      String videoOssIds = '';

      if (_selectedImages.isNotEmpty || _selectedVideos.isNotEmpty) {
        final ossNotifier = ref.read(ossTokenProvider.notifier);

        if (_selectedImages.isNotEmpty) {
          final imagePaths = _selectedImages.map((f) => f.path).toList();
          final imageOssIds = await ossNotifier.uploadFiles(
            imagePaths,
            source: "feedback",
          );
          if (imageOssIds == null) return;
          ossIds = imageOssIds
              .whereType<String>()
              .where((id) => id.isNotEmpty)
              .join(',');
        }

        if (_selectedVideos.isNotEmpty) {
          final videoPaths = _selectedVideos.map((f) => f.path).toList();
          final videoOssIdsList = await ossNotifier.uploadFiles(
            videoPaths,
            source: "feedback",
          );
          if (videoOssIdsList == null) return;
          videoOssIds = videoOssIdsList
              .whereType<String>()
              .where((id) => id.isNotEmpty)
              .join(',');
          ossIds = "$ossIds,$videoOssIds";
        }
      }

      final userInfo = ref.read(userInfoNotifierProvider);

      final request = RequestFeedbackReplyApi(
        feedbackInfoId: widget.feedbackInfoId,
        content: _contentController.text.trim(),
        ossIds: ossIds.isEmpty ? null : ossIds,
        videoOssIds: videoOssIds.isEmpty ? null : videoOssIds,
        appUserId: userInfo.userId.isEmpty ? null : userInfo.userId,
      );

      final submitUsecase = ref.read(replyFeedbackUsecaseProvider);
      await submitUsecase.execute(request);

      if (!mounted) return;
      ToastUtil.show('提交成功');
      Navigator.pop(context);
    } catch (_) {
      if (mounted) {
        ToastUtil.show('提交失败，请稍后重试');
      }
    } finally {
      if (mounted) {
        setState(() {
          _isSubmitting = false;
        });
      }
    }
  }
}

class _VideoThumbnail extends StatefulWidget {
  final String videoPath;

  const _VideoThumbnail({required this.videoPath});

  @override
  State<_VideoThumbnail> createState() => _VideoThumbnailState();
}

class _VideoPreviewScreen extends StatelessWidget {
  final VideoSource videoSource;

  const _VideoPreviewScreen({required this.videoSource});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(title: const Text('视频预览'), backgroundColor: Colors.black),
      body: SafeArea(child: VideoPlayerWidget(source: videoSource)),
    );
  }
}

class _VideoThumbnailState extends State<_VideoThumbnail> {
  VideoPlayerController? _controller;
  bool _isLoading = true;
  bool _hasError = false;

  @override
  void initState() {
    super.initState();
    _loadThumbnail();
  }

  Future<void> _loadThumbnail() async {
    try {
      final uri = Uri.tryParse(widget.videoPath);
      if (uri != null && uri.hasScheme && uri.host.isNotEmpty) {
        _controller = VideoPlayerController.networkUrl(uri);
      } else {
        _controller = VideoPlayerController.file(File(widget.videoPath));
      }
      await _controller!.initialize();
      await _controller!.seekTo(Duration.zero);
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    } catch (_) {
      if (mounted) {
        setState(() {
          _hasError = true;
          _isLoading = false;
        });
      }
    }
  }

  @override
  void dispose() {
    _controller?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (_isLoading) {
      return const Center(child: CircularProgressIndicator(strokeWidth: 2));
    }

    if (_hasError || _controller == null || !_controller!.value.isInitialized) {
      return const Center(child: Icon(Icons.videocam, size: 40));
    }

    return SizedBox.expand(
      child: FittedBox(
        fit: BoxFit.cover,
        child: SizedBox(
          width: _controller!.value.size.width,
          height: _controller!.value.size.height,
          child: VideoPlayer(_controller!),
        ),
      ),
    );
  }
}
